import 'dart:convert';

import 'package:amway_superapp_creator_plugin/analysis/zhuge_identify.dart';

import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/config/config_function.dart';
import 'package:amway_superapp_creator_plugin/config/config_parm.dart';
import 'package:amway_superapp_creator_plugin/config/enum_config.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/event_bus_utils.dart';
import 'package:amway_superapp_creator_plugin/utils/sp_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/create_launch_viewmodel.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:amway_superapp_creator_plugin/widget/customer_share_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';

import '../view_state.dart';

typedef OptionCallback<T> = void Function(dynamic data);

class CreateLaunchView extends StatefulWidget {
  //安利ID
  var amwayId;

  //登陆人的ADA号
  var amwayAda;

  //登录Token
  var token;

  var phone;

  ///
  var adaId;

  ///头像
  var icon;

  ///昵称
  var nickname;

  ///性别
  var gender;

  ///
  var openId;

  ///用户类型
  var accesstype;

  ///城市
  var city;

  ///
  var unionId;

  OptionCallback<Map<String, dynamic>> optionCallback;

  CreateLaunchView({
    @required this.amwayId,
    @required this.amwayAda,
    @required this.token,
    @required this.phone,
    this.optionCallback,
    this.adaId,
    this.icon,
    this.nickname,
    this.gender,
    this.openId,
    this.accesstype,
    this.city,
    this.unionId,
  }) {
    ConfigFunctionCallBack.optionCallback = optionCallback;
    SpUtil.putString("creater_amwayId", amwayId);
    SpUtil.putString("creater_amwayAda", amwayAda);
    ConfigParm.token = token;
    if (amwayId != null && amwayAda != null) {
      ZhugeIdentifyAnalysis.bindUser(
          amwayid: amwayId,
          icon: icon,
          nickname: nickname,
          openid: openId,
          unionid: unionId,
          adaid: amwayId,
          accesstype: accesstype,
          city: city,
          gender: gender);
    }
  }

  @override
  _CreateLaunchViewState createState() => _CreateLaunchViewState();
}

class _CreateLaunchViewState extends State<CreateLaunchView> {
  CreateLaunchViewModel createLaunchViewModel;

  @override
  void deactivate() {
    super.deactivate();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    SpUtil.setData("creater_token", widget.token);
    ConfigParm.token = widget.token;
  }

  @override
  void initState() {
    /* eventBus.on<NoticesEvent>().listen((event) {
      Map<String, dynamic> map = event.datas;
      if (null != map) {
        switch (map['option']) {
          case NotifySuperOption.SHARE:
            widget.optionCallback(map);
            break;
          case NotifySuperOption.REFRSH:
            createLaunchViewModel?.getUserInfo(widget.amwayAda);
            break;
          case NotifySuperOption.TOKENEXPIRE:
            widget.optionCallback(map);
            break;
        }
      }
    });*/
    super.initState();
    HttpManager().init(interceptors: [JWTTokenInterceptor()]);
  }

  @override
  void dispose() {
    eventBus.destroy();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    createLaunchViewModel = CreateLaunchViewModel(api: Provider.of(context));
    return BaseView(
        model: createLaunchViewModel,
        onModelReady: (model) async {
          if (widget.amwayAda == null || widget.amwayId == null) {
            model.createUserInfoModel = null;
            return;
          }
          model.getUserInfo(widget.amwayAda);
          model.queryShareLink(amwayAda: widget.amwayAda);
        },
        builder: (context, model, child) {
          return model.state == ViewState.Idle
              ? Container(
                  width: double.infinity,
                  child: model.isOpenCreate
                      ? buildeOpenCreateView(context, model)
                      : buildeNoOpenCreateView(context, model),
                )
              : Center(
                  child: CircularProgressIndicator(),
                );
        });
  }

  Widget buildeNoOpenCreateView(
      BuildContext context, CreateLaunchViewModel model) {
    return GestureDetector(
      onTap: () {
        if (widget.amwayId == null || widget.amwayAda == null) {
          ToastUtils.showShortToast("获取用户信息失败,请稍后再试");
          return;
        }
        Map<String, dynamic> parameters = {
          'createUserInfoModel': model.createUserInfoModel,
          'amwayAda': widget.amwayAda,
          'amwayId': widget.amwayId,
          'phone': widget.phone,
        };
        if (model.isDraft) {
          Application.router.navigateTo(context, Routes.root,
              routeSettings: RouteSettings(arguments: parameters));
        } else {
          Application.router.navigateTo(context, Routes.CREATESPLASHVIEW,
              routeSettings: RouteSettings(arguments: parameters));
        }
      },
      child: Container(
          margin: EdgeInsets.all(ScreenUtil().setWidth(10)),
          child: Image.asset(
            "picture/banner_img.png",
            fit: BoxFit.cover,
            package: 'amway_superapp_creator_plugin',
          )),
    );
  }

  Widget buildeOpenCreateView(
      BuildContext context, CreateLaunchViewModel model) {
    return Container(
      child: Card(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadiusDirectional.circular(20)),
        clipBehavior: Clip.antiAlias,
        child: Container(
          padding: EdgeInsets.only(
              top: ScreenUtil().setHeight(20),
              left: ScreenUtil().setWidth(20),
              right: ScreenUtil().setWidth(20),
              bottom: ScreenUtil().setHeight(20)),
          child: Column(
            children: [
              Container(
                width: double.infinity,
                padding: EdgeInsets.only(bottom: ScreenUtil().setHeight(10)),
                child: Text(
                  '创玩家空间',
                  textAlign: TextAlign.left,
                  style: TextStyle(fontSize: ScreenUtil().setSp(18)),
                ),
              ),
              Divider(
                height: 1.0,
                indent: 0.0,
                color: Colors.grey[100],
              ),
              GridView.count(
                //水平子Widget之间间距
                shrinkWrap: true,
                // 左右间隔
                crossAxisSpacing: ScreenUtil().setWidth(20),
                mainAxisSpacing: ScreenUtil().setHeight(20),
                //垂直子Widget之间间距
                //GridView内边距
                padding: EdgeInsets.only(
                    top: ScreenUtil().setHeight(10),
                    bottom: ScreenUtil().setHeight(10)),
                //一行的Widget数量
                crossAxisCount: 2,
                //子Widget宽高比例
                childAspectRatio: 2,
                physics: const NeverScrollableScrollPhysics(),
                //子Widget列表
                children: [
                  createItem(
                      lable: "编辑资料",
                      path: "picture/img_lanuch_editer.png",
                      onTap: () {
                        SpUtil.getData("${SpUtil.user_data}${widget.amwayAda}")
                            .then((value) {
                          _jumpEditer(model, context,
                              hasDraft: value == null ? false : true);
                        });
                      }),
                  createItem(
                      lable: "设置小站",
                      path: "picture/img_lanuch_set.png",
                      onTap: () {
                        if (null != model.createUserInfoModel &&
                            null != model.createUserInfoModel.nick &&
                            model.createUserInfoModel.nick.isNotEmpty) {
                          model.createUserInfoModel.amwayId ??= widget.amwayId;
                          Map<String, dynamic> parameters = {
                            'createUserInfoModel': model.createUserInfoModel,
                            'amwayAda': widget.amwayAda,
                            'amwayId': widget.amwayId,
                            'identityMarks':
                                model.createUserInfoModel.identityMarks,
                          };

                          Application.router.navigateTo(
                              context, Routes.mainSettings,
                              routeSettings:
                                  RouteSettings(arguments: parameters));
                        }
                      }),
                  createItem(
                      lable: "分享小站",
                      path: "picture/img_lanuch_share.png",
                      onTap: () {
                        if (null != model.createUserInfoModel &&
                            null != model.createUserInfoModel.nick &&
                            model.createUserInfoModel.nick.isNotEmpty) {
                          CustomerShareView.showShareView(
                              context: context,
                              ada: widget.amwayAda,
                              shareTitle:
                                  model.createUserInfoModel.nick + '邀请你',
                              shareThumbnail: 'picture/img_share_port.png',
                              shareLink: model.shareLink);
                        }
                      }),
                  createItem(
                      lable: "更多配置",
                      path: "picture/img_lanuch_more.png",
                      onTap: () {
                        if (null != model.createUserInfoModel &&
                            null != model.createUserInfoModel.nick &&
                            model.createUserInfoModel.nick.isNotEmpty) {
                          Map<String, dynamic> parameters = {
                            'createUserInfoModel': model.createUserInfoModel,
                            'amwayAda': widget.amwayAda,
                            'amwayId': widget.amwayId,
                          };
                          Application.router.navigateTo(context, Routes.root,
                              routeSettings:
                                  RouteSettings(arguments: parameters));
                        }
                      })
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _jumpEditer(CreateLaunchViewModel model, BuildContext context,
      {bool hasDraft = false}) {
    model.createUserInfoModel.amwayId ??= widget.amwayId;
    Map<String, dynamic> parameters = {
      'createUserInfoModel': model.createUserInfoModel,
      'amwayAda': widget.amwayAda,
      'amwayId': widget.amwayId,
      'hasDraft': hasDraft,
      'phone': widget.phone,
      'isFromLaunch': true,
    };

    Application.router
        .navigateTo(
      context,
      Routes.editdata,
      routeSettings: RouteSettings(arguments: parameters),
    )
        .then((value) {
      if (value != null && value != 1) {
        model.createUserInfoModel = value;
      } else {
        SpUtil.getData("${SpUtil.local_user_data}${widget.amwayAda}")
            .then((value) {
          Map<String, dynamic> response = json.decode(value);
          CreateUserInfoModel infoModel =
              CreateUserInfoModel.fromJson(response);
          if (model.createUserInfoModel != infoModel) {
            model.createUserInfoModel = infoModel;
          }
        });
      }
    });
    /* .then((value) {
      Map<String, dynamic> parameters = {
        'amwayAda': amwayAda,
        'amwayId': amwayId,
      };
      Application.router.navigateTo(
        context,
        Routes.root,
        routeSettings: RouteSettings(arguments: parameters),
      );*/
  }

  ///首页菜单
  Widget createItem({String lable, String path, GestureTapCallback onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        child: Stack(
          children: [
            Align(
              alignment: Alignment.centerRight,
              child: Image.asset(
                path,
                package: 'amway_superapp_creator_plugin',
              ),
            ),
            Align(
              alignment: Alignment.centerLeft,
              child: Text(
                lable,
                style: TextStyle(
                  color: ColorsConfig.c_2c2c2c,
                  fontSize: ScreenUtil().setSp(14),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
